<?php
/**
 * INI file class
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage fs
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
class WakIniFile extends WakTextFile {

    /**
     * return content as associative array
     * with sections support
     * @return array
     */
    public function getData() {
        return parse_ini_file($this->realPath(),true);
    }

    /**
     * converts array to string in INI format
     * @param array $data
     * @return string
     */
    public static function arrayToIni(array $data) {
        $ini='';
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                // is section
                $ini.=chr(13).chr(10).'['.$key.']';
                foreach ($value as $subkey => $subvalue) {
                    $ini.=chr(13).chr(10).self::_iniVarLine($subkey,$subvalue);
                }
            } else {
                $ini.=chr(13).chr(10).self::_iniVarLine($key,$value);
            }
        }
        return $ini;
    }

    /**
     * save content from associative array
     * @param array $data 1-2 levels associative array
     * @return bool
     */
    public function setData(array $data) {
        // erasing file
        if (!$this->erase())
            return false;
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                // is section
                $this->newLine('['.$key.']');
                foreach ($value as $subkey => $subvalue) {
                    $line=self::_iniVarLine($subkey, $subvalue);
                    $this->newLine($line);
                }
            } else {
                $line=self::_iniVarLine($key,$value);
                $this->newLine($line);
            }
        }
        $this->close();
        return true;
    }

    /**
     * builds INI line from a key / value couple
     * @param string $key
     * @param mixed $value
     * @return string
     */
    protected static function _iniVarLine($key,$value) {
        switch (true) {
            case is_bool($value) and $value:
                return $key.' = true';
            case is_bool($value) and !$value:
                return $key.' = false';
            case is_null($value):
                return $key.' = null';
            case is_numeric($value):
                return $key.' = '.strval($value);
            default:
                return $key.' = "'.$value.'"';
        }
    }
}